package in.muton.edushare.poll.reports.excel;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.documentModel.excel.SimpleExcelDocument;
import in.muton.edushare.documentModel.excel.SimpleTable;
import in.muton.edushare.documentModel.excel.StylePalette;
import in.muton.edushare.documentModel.excel.AbsTable.TABLE_POSITION;
import in.muton.edushare.documentModel.excel.StylePalette.CELL_STYLE;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edushare.common.dao.PollStatsDAO;
import com.edushare.common.dao.PollsDAO;
import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.exceptions.ProcessingException;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.Poll;
import com.edushare.common.vo.PollQuestions;
import com.edushare.common.vo.ResponseSummary;
import com.edushare.common.vo.UserPoll;
import com.edushare.common.vo.Users;

/** Might need to be moved to Shared Library */
public class ExcelReport {
	
	private static Log log = LogFactory.getLog(ExcelReport.class);
	
	public static byte[] generateFullReport(Poll p) throws IOException{
		
		SimpleExcelDocument doc = new SimpleExcelDocument("Report");
		ORMInterface ormInterface = EduShareSession.get().getSessionORMInterface();
		
		SimpleTable header = new SimpleTable(doc, 0, 0, TABLE_POSITION.ABSOLUTE_COLUMN);
		header.nextRow();
		header.addCell("Poll Report").setStyle(CELL_STYLE.H4);
		header.nextRow();
		header.addCell(p.getPollName()).setStyle(CELL_STYLE.H1);
		header.nextRow();
		header.nextRow();
		header.addCell("Poll Summary").setStyle(CELL_STYLE.H3);
		header.nextRow();
		
		for(PollQuestions q: p.getQuestions()){
//			Add table for each question and cumulative answer of them
			createSummaryTable(doc, q);
		}
		
		SimpleTable details = new SimpleTable(doc, 2, 0, TABLE_POSITION.ABSOLUTE_COLUMN);
		//create top row
		details.nextRow();
		details.addCell("Individual Responses").setStyle(CELL_STYLE.H3);
		details.nextRow();
		details.nextRow();
		details.addCell("Voters/Questions").setStyle(CELL_STYLE.TABLE_HEADER);
		for(int i=1; i<=p.getQuestions().size(); i++)
			details.addCell("Question: "+i).setStyle(CELL_STYLE.TABLE_HEADER);
		int index = 0;
		for(Users u: p.getVotersByStatus(UserPoll.POLL_COMPLETE)){
			details.nextRow();
			index++;
			//User Cell
			if(p.getPollAnonymous() == Poll.ANONYMOUS_POLL)
				details.addCell("Respondent "+index);
			else
				details.addCell(u.getCompleteUserName()+" ("+u.getUserName()+")");
			//question responses
			int questionNum = p.getQuestions().size();
			for(int i=1;i<=questionNum;i++){
				PollQuestions pq = new PollsDAO(ormInterface).getQuestionBySNo(p, i);
				UserPollDAO updDao = new UserPollDAO(ormInterface);
				List<String> sl = updDao.getUserAnswerReportAsList(u, pq);
				String s = "";
				if(sl!=null && sl.size()>0){
					for(int j=0; j<sl.size(); j++){
						if(j>0)
							s = s + System.getProperty("line.separator");
						s = s + sl.get(j);
					}
				}
				details.addCell(s);
				details.setStyle(StylePalette.CELL_STYLE.LONG_TEXT);
			}
		}
		
		return doc.getWorkbookAsByteArray(true);
	}

	private static void createSummaryTable(SimpleExcelDocument doc, PollQuestions q) {
		SimpleTable table = new SimpleTable(doc, 1, 0, TABLE_POSITION.ABSOLUTE_COLUMN);
		table.nextRow();
		table.addCell("Question " + q.getQuestionSerialNo()+": ").setStyle(CELL_STYLE.BOLD);
		table.addCell(q.getQuestion()).setStyle(CELL_STYLE.BOLD);
		// new row
		table.nextRow();
		if(q.isResponseSummarizable()){
			summarize(table, q);
		}else{
			table.addCell("Summary not available.");
		}
	}

	private static void summarize(SimpleTable table, PollQuestions q) {
		try {
			List<ResponseSummary> respl = new PollStatsDAO(EduShareSession.get().getSessionORMInterface())
											.getSummarizedResponse(q);
			//generate header
			table.addCell("");
			table.addCell("Option").setStyle(CELL_STYLE.TABLE_HEADER);
			table.addCell("Votes").setStyle(CELL_STYLE.TABLE_HEADER);
			if(q.getQuestionType() == PollQuestions.QUESTION_TYPE_RATING)
				table.addCell("Average Rating").setStyle(CELL_STYLE.TABLE_HEADER);
			else
				table.addCell("Percentage").setStyle(CELL_STYLE.TABLE_HEADER);
			//generate Data
			for(ResponseSummary rs: respl){
				table.nextRow();
				table.addCell("");
				table.addCell(rs.getResponseText());
				table.addCell(rs.getVotes());
				if(q.getQuestionType()==PollQuestions.QUESTION_TYPE_RATING)
					table.addCell(rs.getRating());
				else
					table.addCell(rs.getPercent());
			}
		} catch (ProcessingException e) {
			log.warn("Error while getting the summary. " +
					"Is it a mathematically summarizable " +
					"question? \""+q.getQuestion()+"\" Type: " +
					""+q.getQuestionType(), e);
		}
	}
}
